package com.gykfbxxh.imovie.utils;

import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.widget.ImageView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.app.utils.util.GsonUtils;
import com.app.utils.util.StringUtils;
import com.app.utils.util.net.NetUtils;
import com.gykfbxxh.imovie.config.AppConfigTools;
import com.gykfbxxh.imovie.custom.net.GsonGetRequest;
import com.gykfbxxh.imovie.custom.net.GsonGetResultRequest;
import com.gykfbxxh.imovie.custom.net.GsonPostRequest;
import com.gykfbxxh.imovie.custom.net.GsonPostResultRequest;
import com.gykfbxxh.imovie.custom.net.ParamMap;
import com.gykfbxxh.imovie.listener.HttpListener;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Map;


/**
 * 自定制的请求网络类
 * Created by xuxinghai on 2016/7/15.
 */
public class HttpUtils {

    /**
     * 发送一个get网络请求 返回result
     * @param url 请求地址 不为空,否则执行失败回调
     * @param requestName 请求标识
     * @param httpListener 回调监听 无回调可为null
     */
    public static void addGetResultRequest(@NonNull String url,String requestName,HttpListener<String> httpListener){
        GsonGetResultRequest gsonGetResultRequest;
        if(httpListener==null) {
            gsonGetResultRequest = new GsonGetResultRequest(
                    url,
                    GsonUtils.getInstance().getGson(),
                    null,
                    null);
        }else {
            httpListener.onStart();//开始请求
            gsonGetResultRequest = new GsonGetResultRequest(
                    url,
                    GsonUtils.getInstance().getGson(),
                    httpListener.getSucesListener(),
                    httpListener.getErrorListener());
        }
        gsonGetResultRequest.setShouldCache(false);//不使用缓存
        NetUtils.getInstance().addRequest(gsonGetResultRequest, requestName);
    }


    /**
     * 发送一个post网络请求
     *
     * @param url          请求地址 不为空,否则执行失败回调
     * @param requestName  请求标识
     * @param parms        请求参数 可为空(无参数可传null)
     * @param httpListener 回调监听 可为空(无回调可为null)
     */
    public static void addPostResultRequest(@NonNull String url,  String requestName, Map<String, String> parms, HttpListener<String> httpListener) {

        GsonPostResultRequest gsonPostRequest;
        if (httpListener == null) {
            gsonPostRequest = new GsonPostResultRequest(
                    url,
                    parms,
                    GsonUtils.getInstance().getGson(),
                    null,
                    null);

        }else{
            httpListener.onStart();
            gsonPostRequest = new GsonPostResultRequest(
                    url,
                    parms,
                    GsonUtils.getInstance().getGson(),
                    httpListener.getSucesListener(),
                    httpListener.getErrorListener());
        }
        gsonPostRequest.setShouldCache(false);//不使用缓存
        NetUtils.getInstance().addRequest(gsonPostRequest, requestName);
    }

    /**
     * 发送一个带缓存的post网络请求
     *
     * @param url          请求地址 不为空,否则执行失败回调
     * @param requestName  请求标识
     * @param parms        请求参数 可为空(无参数可传null)
     * @param httpListener 回调监听 可为空(无回调可为null)
     */
    public static void addPostCacheResultRequest(@NonNull String url, String requestName, Map<String, String> parms, HttpListener<String> httpListener) {
        GsonPostResultRequest gsonPostRequest;
        if (httpListener == null) {
            gsonPostRequest = new GsonPostResultRequest(
                    url,
                    parms,
                    GsonUtils.getInstance().getGson(),
                    null,
                    null);

        }else{
            httpListener.onStart();
            gsonPostRequest = new GsonPostResultRequest(
                    url,
                    parms,
                    GsonUtils.getInstance().getGson(),
                    httpListener.getSucesListener(),
                    httpListener.getErrorListener());
        }

        gsonPostRequest.setShouldCache(true);//使用缓存
        NetUtils.getInstance().addRequest(gsonPostRequest, requestName);
    }



    /**
     * 发送一个get网络请求
     *
     * @param url          请求地址 不为空,否则执行失败回调
     * @param type         数据类型
     * @param requestName  请求标识
     * @param httpListener 回调监听 无回调可为null
     */
    public static void addGetRequest(@NonNull String url, @NonNull Type type, String requestName, HttpListener<?> httpListener) {

        GsonGetRequest gsonGetRequest;
        if (httpListener == null) {
            gsonGetRequest = new GsonGetRequest(
                    url,
                    type,
                    GsonUtils.getInstance().getGson(),
                    null,
                    null);
        }else{
            httpListener.onStart();//开始请求
            gsonGetRequest = new GsonGetRequest(
                    url,
                    type,
                    GsonUtils.getInstance().getGson(),
                    httpListener.getSucesListener(),
                    httpListener.getErrorListener());
        }
        gsonGetRequest.setShouldCache(false);//不使用缓存
        NetUtils.getInstance().addRequest(gsonGetRequest, requestName);

    }



    /**
     * 发送一个post网络请求
     *
     * @param url          请求地址 不为空,否则执行失败回调
     * @param type         数据类型 不为空,否则执行失败回调
     * @param requestName  请求标识
     * @param parms        请求参数 可为空(无参数可传null)
     * @param httpListener 回调监听 可为空(无回调可为null)
     */
    public static void addPostRequest(@NonNull String url, @NonNull Type type, String requestName, Map<String, String> parms, HttpListener<?> httpListener) {

        GsonPostRequest gsonPostRequest;
        if (httpListener == null) {
            gsonPostRequest = new GsonPostRequest(
                    url,
                    parms,
                    type,
                    GsonUtils.getInstance().getGson(),
                    null,
                    null);

        }else{
            httpListener.onStart();
            gsonPostRequest = new GsonPostRequest(
                    url,
                    parms,
                    type,
                    GsonUtils.getInstance().getGson(),
                    httpListener.getSucesListener(),
                    httpListener.getErrorListener());
        }
        gsonPostRequest.setShouldCache(false);//不使用缓存
        NetUtils.getInstance().addRequest(gsonPostRequest, requestName);
    }

    /**
     * 发送一个带缓存的post网络请求
     *
     * @param url          请求地址 不为空,否则执行失败回调
     * @param type         数据类型 不为空,否则执行失败回调
     * @param requestName  请求标识
     * @param parms        请求参数 可为空(无参数可传null)
     * @param httpListener 回调监听 可为空(无回调可为null)
     */
    public static void addPostCacheRequest(@NonNull String url, @NonNull Type type, String requestName, Map<String, String> parms, HttpListener<?> httpListener) {
        GsonPostRequest gsonPostRequest;
        if (httpListener == null) {
            gsonPostRequest = new GsonPostRequest(
                    url,
                    parms,
                    type,
                    GsonUtils.getInstance().getGson(),
                    null,
                    null);

        }else{
            httpListener.onStart();
            gsonPostRequest = new GsonPostRequest(
                    url,
                    parms,
                    type,
                    GsonUtils.getInstance().getGson(),
                    httpListener.getSucesListener(),
                    httpListener.getErrorListener());
        }

        gsonPostRequest.setShouldCache(true);//使用缓存
        NetUtils.getInstance().addRequest(gsonPostRequest, requestName);
    }

    /**
     * 加载图片(带加载监听)
     * @param url
     * @param requestName
     * @param maxWidth
     * @param maxHeight
     * @param listener
     * @param errorListener
     */
    public static void addImageRequest(@NonNull String url, String requestName,int maxWidth, int maxHeight
            ,@NonNull Response.Listener<Bitmap> listener,Response.ErrorListener errorListener) {
        ImageRequest imageRequest = new ImageRequest(
                url,
                listener,
                maxWidth,
                maxHeight,
                Bitmap.Config.RGB_565,
                errorListener);
        imageRequest.setShouldCache(true);
        NetUtils.getInstance().addRequest(imageRequest, requestName);
    }

    /**
     * 加载图片(不带带加载监听)
     * @param url
     * @param imageView
     * @param requestName
     */
    public static void addImageRequest(@NonNull String url,@NonNull final ImageView imageView, String requestName) {
        ImageRequest imageRequest = new ImageRequest(
                url,
                new Response.Listener<Bitmap>()

                {
                    @Override
                    public void onResponse(Bitmap response) {
                        if (response != null && imageView != null) {
                            imageView.setImageBitmap(response);
                        }
                    }
                },
                0,
                0,
                Bitmap.Config.RGB_565,
                new Response.ErrorListener()

                {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        imageRequest.setShouldCache(true);
        NetUtils.getInstance().addRequest(imageRequest, requestName);
    }



    /**
     * 退出指定的网络请求
     *
     * @param tag
     */
    public static void cancelAllRequests(@NonNull final String tag) {
        NetUtils.getInstance().cancelAllRequests(tag);
    }


    /**
     * map包装类的md5加密
     * @param parmsMap
     */
    public static void ParmsMapMD5(ParamMap parmsMap){
        if(parmsMap == null){
            return;
        }
        //生成时间戳
        String timestamp =""+ System.currentTimeMillis() ;
        //加入时间戳参数
//        parmsMap.putEncode("timestamp", timestamp);
        Object[] key   =  parmsMap.keySet().toArray();
        if(key == null || key.length == 0){
            return;
        }
        Arrays.sort(key);//升序排列
        //待加密字符串
        StringBuffer verifyMsg = new StringBuffer();

        //倒序输出
        for (int i = key.length - 1; i >= 0; i--) {
            verifyMsg.append(key[i] + "=" + parmsMap.get(key[i]) + "&");
        }

        //拼接版本标识
        verifyMsg.append(AppConfigTools.APICODE);

        //进行MD5加密
        String verifyMsgMd5 = StringUtils.md5(verifyMsg.toString());
        //加入加密字符串参数
//        parmsMap.put("verifyMsg",verifyMsgMd5);
    }





//    /**
//     * 针对于上传文件的加密方法
//     * @param multipartBuilder
//     * @param params
//     */
//    public static void UploadMD5Encryption(MultipartBuilder multipartBuilder,Map<String,String> params,String fileKey){
//        //生成时间戳
//        String timestamp =""+ System.currentTimeMillis() ;
//        //加入时间戳参数
//        params.put("timestamp", timestamp);
//
//        multipartBuilder.addFormDataPart("timestamp", timestamp);
//        multipartBuilder.addFormDataPart(fileKey, fileKey);
//
//        Object[] key   =  params.keySet().toArray();
//        if(key == null || key.length == 0){
//            return;
//        }
//        Arrays.sort(key);//升序排列
//        //待加密字符串
//        StringBuffer verifyMsg = new StringBuffer();
//        //倒序输出
//        try {
//            for(int i=key.length-1;i>=0;i--){
//                verifyMsg.append(key[i] + "=" + URLEncoder.encode(params.get(key[i]).toString(),"utf-8")  + "&");
//            }
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        //拼接版本标识
//        verifyMsg.append(AppConfigTools.APICODE);
//        //进行MD5加密
//        String verifyMsgMd5 = StringUtils.md5(verifyMsg.toString());
//        //parmsMap.put("verifyMsg",verifyMsgMd5);
//        multipartBuilder.addFormDataPart("verifyMsg", verifyMsgMd5);
//    }



//    public static void UploadMD5Encryption(MultipartBuilder multipartBuilder,Map<String,String> params,String fileKey){
//        //生成时间戳
//        String timestamp =""+ System.currentTimeMillis() ;
//        //加入时间戳参数
//        params.put("timestamp", timestamp);
//
//        multipartBuilder.addFormDataPart("timestamp", timestamp);
//        multipartBuilder.addFormDataPart(fileKey, fileKey);
//
//        Object[] key   =  params.keySet().toArray();
//        if(key == null || key.length == 0){
//            return;
//        }
//        Arrays.sort(key);//升序排列
//        //待加密字符串
//        StringBuffer verifyMsg = new StringBuffer();
//        //倒序输出
//        try {
//            for(int i=key.length-1;i>=0;i--){
//                verifyMsg.append(key[i] + "=" + URLEncoder.encode(params.get(key[i]).toString(),"utf-8")  + "&");
//            }
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        //拼接版本标识
//        verifyMsg.append(AppConfigTools.APICODE);
//        //进行MD5加密
//        String verifyMsgMd5 = StringUtils.md5(verifyMsg.toString());
//        //parmsMap.put("verifyMsg",verifyMsgMd5);
//        multipartBuilder.addFormDataPart("verifyMsg", verifyMsgMd5);
//    }


}
